<!--
* @author: XJC
* @date: 2023-11-27 13:59
* @description：index
* @update: 2023-11-27 13:59
-->
<template>
  <div class='smartShelves' ref='smartShelves' >
    <img class='b-top' src='@/assets/shelf_manage_img/shelf-top.png' />
    <img class='b-top b-topy' src='@/assets/shelf_manage_img/shelf-top-yy.png' />
    <img class='b-left' src='@/assets/shelf_manage_img/shelf-left.png' />
    <img class='b-right' src='@/assets/shelf_manage_img/shelf-right.png' />
    <div class='storey flex'
         :class='{"is-disabled":isCheck&&showMergeCheckbox&&currentRowIndex!==lIndex,"storey2":layer.high===2}'
         v-for='(layer, lIndex) in shelves.layerList'
         :key='layer.id'>
      <div class='article flex flex-space-between'>
        <div class='article-box flex flex-center'
             :style="[{ flex: position.mergeId ? position.mergeCount : '1' }]"
             v-for='(position, index) in layer.positionList'
             :key='position.id'>
          <div class='article-box-item flex flex-center' @click='chooseItem(position)'
               :class='{"select":selectPositionId===position.id,"select-red":computeRed(position)}'
               :style="{width:(isSmall ? articleWidth:'')}">
            <!-- 合并显示 :disabled='isCheck&&currentRowIndex!==lIndex'-->
            <el-checkbox
              @change='changeMerge($event, position,lIndex,index,layer.positionList.length,layer.positionList)'
              :disabled='checkedBoxDisableArr[index]'
              v-model='position.check'
              v-if='showMergeCheckbox&&!position.goodsId&&!position.mergeId&&checkedBoxIndexArr[index]&&(!isCheck||currentRowIndex===lIndex)'
              class='checkbox'></el-checkbox>
            <!-- 拆分显示-->
            <el-checkbox
              @change='changeMerge($event, position,lIndex,index,layer.positionList.length,layer.positionList)'
              v-model='position.check'
              v-if='showSplitCheckbox&&position.mergeId&&!position.goodsId' class='checkbox'></el-checkbox>
            <!--手动领用或归还显示-->
            <el-checkbox
              @change='collectOrReturnChangeMerge($event, position,lIndex)'
              v-model='position.check'
              v-if='collectOrReturn&&position.goodsId'
              class='checkbox'></el-checkbox>
            <!--新增显示默认图-->
            <img v-if='isAdd||isBrowse' class='logo' src='@/assets/shelf_manage_img/shelf-item.png' />
            <!--显示物品图片-->
            <img v-if='!isAdd&&position.goodsId&&!position.goodsImage' @click='unBinding(position)' class='logo'
                 src='@/assets/shelf_manage_img/goods-default.png' />
            <img v-if='!isAdd&&position.goodsId&&position.goodsImage' @click='unBinding(position)' class='logo'
                 :src='position.goodsImage' />
            <!--显示添加图片-->
            <div @click.stop='bindItems(position)' v-if='!isAdd&&!isBrowse&&!position.goodsId'
                 class='article-box-item-add'></div>
            <!--合并显示显示物品量程-->
            <div class='article-box-item-weight' v-if='showMergeCheckbox&&!position.goodsId&&!position.mergeId'>
              {{ position.weightMaxAll ? position.weightMaxAll : position.weightMax }}g
            </div>
          </div>
          <!--合并显示显示连接线-->
          <div class='v-line' v-if='position.mergeId'></div>
          <div class='h-line'
               :style="{ width: (lampWidth / realPositionListNum(lIndex).num) * (position.mergeCount - 1) + 'px' }"
               v-if='position.mergeId'></div>
        </div>
      </div>
      <div class='lamp flex flex-space-between'>
        <div class='lamp-box flex flex-center'
             v-for='rIndex in realPositionListNum(lIndex).num'
             :key='rIndex'>
          <div class='lamp-box-item' :class='{"color-1":realPositionListNum(lIndex).isRed[rIndex-1]}'></div>
        </div>
      </div>
    </div>
    <el-empty v-if='shelves.layerList.length === 0'
              :image-size='400'
              description='请先配置数据'
    ></el-empty>
  </div>
</template>

<script>
export default {
  name: 'index',
  components: {},
  props: {
    smartIndex:{
      type: Number,
      default: 0
    },
    // 货架数据
    shelves: {
      type: Object,
      default() {
        return {}
      }
    },
    // 是否显示合并复选框
    showMergeCheckbox: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 是否显示拆分复选框
    showSplitCheckbox: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 是否显示添加按钮
    isAdd: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 货物宽度
    articleWidth: {
      type: String,
      default() {
        return '70px'
      }
    },
    // 是否是小货架
    isSmall: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 是否是浏览模式
    isBrowse: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 物料选中的id
    selectPositionId: {
      type: String,
      default() {
        return ''
      }
    },
    // 手动领用或归还
    collectOrReturn: {
      type: Boolean,
      default() {
        return false
      }
    },
  },
  data() {
    return {
      // 灯的宽度
      lampWidth: 1000,
      loading: true,
      // 合并/拆分选中的物品
      selectArr: [],
      // 当前行下标
      currentRowIndex: 999,
      // 当前行是否选中
      isCheck: false,
      // 合并左右的复选框是否显示
      checkedBoxIndexArr: {
        0: true,
        1: true,
        2: true,
        3: true,
        4: true,
        5: true,
        6: true,
        7: true,
        8: true,
        9: true
      },
      // 合并左右的复选框是否禁用-不同量程的货架不能合并
      checkedBoxDisableArr: {
        0: false,
        1: false,
        2: false,
        3: false,
        4: false,
        5: false,
        6: false,
        7: false,
        8: false,
        9: false
      },
      // 真正合并选中的下标
      realSelectIndexArr: [],
      // 手动领用或归还选中的数据
      collectOrReturnData: []
    }
  },
  // 计算属性（类似于data概念）
  computed: {},

  // 过滤器
  filters: {},

  // 监视器（监视data中的数据变化）
  watch: {
    selectArr(val) {
      if (val.length > 0) {
        this.isCheck = true
      } else {
        this.isCheck = false
        this.currentRowIndex = 999
        this.realSelectIndexArr = []
        this.checkedBoxIndexArr = {
          0: true,
          1: true,
          2: true,
          3: true,
          4: true,
          5: true,
          6: true,
          7: true,
          8: true,
          9: true
        }
        this.checkedBoxDisableArr = {
          0: false,
          1: false,
          2: false,
          3: false,
          4: false,
          5: false,
          6: false,
          7: false,
          8: false,
          9: false
        }
      }
    },
    showMergeCheckbox(val) {
      if (!val && this.currentRowIndex !== 999) {
        this.shelves.layerList[this.currentRowIndex].positionList.forEach((item) => {
          item.check = false
        })
        this.selectArr = []
      }
    },
    showSplitCheckbox(val) {
      if (!val) {
        this.shelves.layerList.forEach((item) => {
          item.positionList.forEach((item2) => {
            item2.check = false
          })
        })
        this.selectArr = []
      }
    },
    collectOrReturn(val) {
      if (!val) {
        this.shelves.layerList.forEach((item) => {
          item.positionList.forEach((item2) => {
            item2.check = false
          })
        })
        this.collectOrReturnData = []
      }
    }
  },

  // 方法合集
  methods: {
    computeRed(item) {
      if (item.goodsSingleWeight || item.goodsStock) {
        // 绑定东西了
        // 超重
        let r1 = item.goodsStock * item.goodsSingleWeight > parseInt(item.weightMax)
        // 缺货
        let r2 = item.goodsTotalStock <= item.goodsWarnCount
        return (r1 || r2) && this.selectPositionId === item.id
      } else {
        return false

      }
    },
    // 获取真实的货架数量
    realPositionListNum(index) {
      let num = 0
      let id = 0
      let isRed = []
      this.shelves.layerList[index].positionList.forEach((item) => {
        if (item.mergeId) {
          num += Number(item.mergeCount)
        } else {
          num += 1
        }
        let isRed2 = false

        if (item.goodsSingleWeight || item.goodsStock) {
          // 绑定东西了
          // 超重
          let r1 = item.goodsStock * item.goodsSingleWeight > parseInt(item.weightMax)
          // 缺货
          let r2 = item.goodsTotalStock <= item.goodsWarnCount
          isRed2 = r1 || r2
          for (var i = 0; i < Number(item.mergeCount); i++) {
            isRed.push(isRed2)
          }
        } else {
          isRed2 = false
          isRed.push(isRed2)
        }

        id = item.id
      })
      return { num: num, id: id, isRed: isRed }
    },
    // 绑定物品
    bindItems(item) {
      if (this.showMergeCheckbox || this.showSplitCheckbox) return
      this.$emit('bindItems', item)
    },
    // 解绑物品
    unBinding(item) {
      if (this.showMergeCheckbox || this.showSplitCheckbox || this.isBrowse) return
      this.$emit('unBinding', item)
    },
    // 选中物品
    chooseItem(item) {
      if (this.collectOrReturn) return
      this.$emit('chooseItem', item)
    },
    // 手动领用或归还选中
    collectOrReturnChangeMerge(val, item, layerSort) {
      if (val) {
        item['layerSort'] = layerSort + 1
        console.log(item)
        this.collectOrReturnData.push(item)
      } else {
        this.collectOrReturnData.splice(this.collectOrReturnData.indexOf(item), 1)
      }
      this.$forceUpdate()
      this.$emit('collectOrReturnChangeMerge', this.collectOrReturnData,this.smartIndex, item)
    },
    /**
     * @description: 选中合并
     * @param {Boolean} val 是否选中
     * @param {Object} item 当前物品
     * @param {Number} lIndex 当前行下标
     * @param {Number} index 当前物品下标
     * @param {Number} length 当前层有几个
     * @param {Array} layer 当前层
     * @return {*}
     */
    changeMerge(val, item, lIndex, index, length, layer) {
      if (lIndex !== this.currentRowIndex) {
        this.checkedBoxIndexArr = {}
        this.checkedBoxDisableArr = {}
        for (let i = 0; i < length; i++) {
          this.checkedBoxIndexArr[i] = false
          this.checkedBoxDisableArr[i] = false
        }
      }
      this.currentRowIndex = lIndex
      this.checkedBoxIndexArr[index] = val
      if (val) {
        this.realSelectIndexArr.push(index)
        this.realSelectIndexArr.sort()
        this.selectArr.push(item)
        // this.$set(layer[index], 'check', true)
        if (index > 0) {
          this.checkedBoxIndexArr[index - 1] = true
          if (layer[index].weightMax !== layer[index - 1].weightMax) {
            this.checkedBoxDisableArr[index - 1] = true
          }
        }
        if (index < length - 1) {
          this.checkedBoxIndexArr[index + 1] = true
          if (layer[index].weightMax !== layer[index + 1].weightMax) {
            this.checkedBoxDisableArr[index + 1] = true
          }
        }
      } else {
        this.realSelectIndexArr.splice(this.realSelectIndexArr.indexOf(index), 1)
        if (this.realSelectIndexArr.length > 0) {
          let {
            longestSubarray,
            remainingElements
          } = this.findLongestContinuousSubarray(this.realSelectIndexArr, index)
          this.realSelectIndexArr = longestSubarray
          this.selectArr = []
          // 全部取消选中
          for (let i = 0; i < remainingElements.length; i++) {
            layer[remainingElements[i]].check = false
          }
          // 将最长连续子数组选中
          for (let i = 0; i < longestSubarray.length; i++) {
            this.selectArr.push(layer[longestSubarray[i]])
            layer[longestSubarray[i]].check = true
          }
          for (let i = 0; i < length; i++) {
            this.checkedBoxIndexArr[i] = false
          }
          for (let i = 0; i < longestSubarray.length; i++) {
            this.checkedBoxIndexArr[longestSubarray[i]] = true
            if (longestSubarray[i] > 0) {
              this.checkedBoxIndexArr[longestSubarray[i] - 1] = true
            }
            if (longestSubarray[i] < length - 1) {
              this.checkedBoxIndexArr[longestSubarray[i] + 1] = true
            }
          }
        } else {
          this.selectArr = []
          for (let i = 0; i < length; i++) {
            layer[i].check = false
          }
        }
      }
      this.$forceUpdate()
      let mergeStr = ''
      if (this.showMergeCheckbox) {
        for (let i = 0; i < this.realSelectIndexArr.length; i++) {
          let nums=0
          for (let j = 0; j < this.realSelectIndexArr[i]; j++) {
            nums+=layer[j].mergeId?Number(layer[j].mergeCount):1
          }
          // let num = Number(this.realSelectIndexArr[i]) + 1 +nums
          let num = Number(nums) + 1
          let str = lIndex + 1 + '层' + num + '号位' + '、'
          mergeStr += str
        }
        mergeStr = mergeStr.substring(0, mergeStr.length - 1)
      }
      this.$emit('changeMerge', this.selectArr, mergeStr)
    },
    // 寻找最长连续子数组
    findLongestContinuousSubarray(arr, index) {
      let longestSubarray = []
      let currentSubarray = [arr[0]]
      for (let i = 1; i < arr.length; i++) {
        if (arr[i] === arr[i - 1] + 1) {
          currentSubarray.push(arr[i])
        } else {
          // 更新最长子数组
          if (currentSubarray.length > longestSubarray.length) {
            longestSubarray = [...currentSubarray]
          }
          currentSubarray = [arr[i]]
        }
      }
      // 检查最后一个子数组
      if (currentSubarray.length > longestSubarray.length) {
        longestSubarray = [...currentSubarray]
      }
      // 从原始数组中移除最长子数组的元素
      const remainingElements = arr.filter(element => !longestSubarray.includes(element))
      remainingElements.push(index)
      return { longestSubarray, remainingElements }
    },
    // 获取窗口大小
    getWindowSize() {
      this.lampWidth = this.$refs.smartShelves.offsetWidth
    }
  },

  // 生命周期 - 创建完成（可以访问当前this实例，完成了data 数据的初始化，可以访问data、computed、watch、methods上的方法和数据。但是，未挂载到DOM，不能访问到el属性，el属性，ref属性内容为空。）
  created() {
  },

  // 生命周期 - 挂载完成（可以访问DOM元素，一般在此执行：开启定时器，发送网络请求，订阅消息，绑定自定义事件等初始化操作。）
  mounted() {
    this.$nextTick(() => {
      this.lampWidth = this.$refs.smartShelves.offsetWidth
    })
    // 监听窗口大小变化
    window.addEventListener('resize', this.getWindowSize)
  },
  // 生命周期-页面销毁前（在销毁前，实例中所有的data、methods、computed、指令等，都处于可用状态在此阶段，一般进行：关闭定时器、取消订阅消息解绑自定义事件等收尾工作。）
  beforeDestroy() {
    // 组件销毁前移除事件监听
    window.removeEventListener('resize', this.getWindowSize)
  }
}
</script>

<style scoped lang='scss'>
@import '@/styles/_handle.scss';

.smartShelves {
  width: 100%;
  height: 1100px;
  padding-top: 30px;
  display: flex;
  flex-direction: column;
  background-image: url('~@/assets/shelf_manage_img/shelf-bg.png');
  position: relative;

  .b-top {
    width: 100%;
    height: 30px;
    top: 0;
    position: absolute;
    z-index: 10;
  }

  .b-left {
    width: 30px;
    height: 100%;
    top: 0;
    left: 0;
    position: absolute;
  }

  .b-right {
    width: 30px;
    height: 100%;
    top: 0;
    right: 0;
    position: absolute;
  }

  .b-topy {
    top: 30px;
    width: calc(100% - 40px);
    left: 50%;
    transform: translateX(-50%);
  }

  .storey {
    width: 100%;
    flex: 1;
    //overflow: hidden;
    flex-direction: column;
    transition: opacity 0.3s ease-in-out;

    .article {
      flex: 1;
      margin: 0 20px;

      &-box {
        flex: 1;
        //aspect-ratio: 1;
        position: relative;
        //overflow: hidden;


        &-item {
          width: 70px;
          aspect-ratio: 1;
          margin: 0 auto;
          text-align: center;
          position: relative;
          background: linear-gradient(180deg, #fafafa 0%, #f1f1f1 86%);
          box-shadow: 0px 2px 0px 0px rgba(0, 24, 50, 0.5);
          border-radius: 8px;
          border: 2px solid #b0b0b0;
          z-index: 30;
          cursor: pointer;

          &-weight {
            width: 100%;
            font-size: 16px;
            color: #001832;
            text-align: center;
            position: absolute;
            font-weight: 600;
            bottom: -25px;
          }

          &-add {
            width: 38px;
            height: 38px;
            background: linear-gradient(180deg, #fafafa 0%, #f1f1f1 86%);
            box-shadow: 0px 1px 0px 0px rgba(0, 24, 50, 0.5);
            border-radius: 8px;
            border: 2px solid #b0b0b0;
            position: relative;
            cursor: pointer;

            &::before,
            &::after {
              content: "";
              position: absolute;
              @include background_color("basic_color");
            }

            &::before {
              width: 8px;
              height: 80%;
              left: 50%;
              top: 10%;
              transform: translateX(-50%);
            }

            &::after {
              width: 80%;
              height: 8px;
              top: 50%;
              left: 10%;
              transform: translateY(-50%);
            }
          }

          .checkbox {
            position: absolute;
            top: -10px;
            right: -10px;
            z-index: 10;
          }

          ::v-deep .el-checkbox__inner {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            border: 2px solid;
            @include border_color("basic_color");
            background: #e2f0ff;
          }

          ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
            background: #e2f0ff;
            border-radius: 50%; //对边框进行调整
          }

          ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner::after {
            @include border_color("basic_color"); //里面内容的颜色
            border-width: 3px; //对里面的对号做一个加粗
            width: 10px;
            height: 18px;
            left: 7px;
          }

          ::v-deep .el-checkbox__input.is-disabled .el-checkbox__inner {
            background: #848485;
            border-radius: 50%; //对边框进行调整
            border-color: #000000 !important;
          }


          .logo {
            width: 80%;
            height: 80%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }
        }

        .select {
          @include border_color("basic_color");
          border: 4px solid;
        }

        .select-red {
          @include border_color("err_color");
          border: 4px solid;
        }

        .v-line {
          width: 2px;
          height: 50%;
          @include background_color("basic_color");
          position: absolute;
          bottom: -15px;
          z-index: 20;
        }

        .h-line {
          width: 50%;
          height: 2px;
          @include background_color("basic_color");
          position: absolute;
          bottom: -15px;
          z-index: 20;

          &-item {
            width: 2px;
            height: 100%;
            @include background_color("basic_color");
            position: relative;
          }
        }
      }
    }

    .lamp {
      margin: 0 20px;
      z-index: 10;
      height: 30px;
      background-image: url('~@/assets/shelf_manage_img/shelf-center.png');
      position: relative;

      &-box {
        flex: 1;
        position: relative;

        &-item {
          width: 20px;
          height: 20px;
          @include background_color("basic_color");
          border-radius: 4px;
        }

        .color-1 {
          background: #FF1F06 !important;
        }
      }

      &:after {
        content: '';
        width: 100%;
        height: 30px;
        position: absolute;
        top: 30px;
        left: 0;
        background-image: url('~@/assets/shelf_manage_img/shelf-top-yy.png');
        background-size: 100% 100%;
        z-index: 20;
      }
    }
  }

  .storey2 {
    flex: 2;
  }

  .is-disabled {
    opacity: 0.4;
  }

  &:last-child {
    .storey:last-child {
      .lamp {
        &:after {
          display: none;
        }
      }
    }
  }
}
</style>
